import { sysJournalCollectAdd } from '@/api/home/sysJournalCollect'
import JSZip from 'jszip'
import moment from 'moment'
export default {
  data() {
    return {
      waterQuery: {
        id: '',
        text: '',
        fontSize: '',
        x: '',
        y: '',
        r: '',
        green: '',
        red: '',
        blue: '',
        f: '',
      },
    }
  },
  methods: {
    //下载一篇文章
    async downloadOne(articleObj) {
      let { fileList } = articleObj
      if (!fileList.length) return
      await this.getWatermarkInfo()
      fileList.forEach(async (v) => {
        let res = await this.getBlobPms(v)
        this.saveAs(res, v.oldName)
      })
      this.addDownloadCount(articleObj.id, 2)
    },
    //下载一本
    async handleDownloadBook(journalObj) {
      let { id, pdfInfo } = journalObj
      if (!pdfInfo) {
        this.warnMsg('暂无下载内容')
        return
      }
      let res = await this.getBlobPms(pdfInfo)
      this.saveAs(res, pdfInfo.oldName)
      this.addDownloadCount(id, 1)
    },
    //下载多本
    async handleDownloadMoreBook(journalList, zipName) {
      //过滤掉没有上传整本pdf的数据
      let hasPdfList = journalList.filter((v) => v.hasOwnProperty('pdfInfo'))
      if (!journalList.length || !hasPdfList.length) {
        this.warnMsg('暂无下载内容')
        return
      }
      hasPdfList.forEach((v) => {
        this.addDownloadCount(v.id, 1)
      })
      //拿到数组中pdf数组
      let fileList = hasPdfList.map((v) => v.pdfInfo)
      let nw = moment(new Date()).format('YYYYMMDDHHmmss')
      await this.getWatermarkInfo()
      this.downloadByZip(fileList, zipName || nw)
    },
    //压缩
    async downloadByZip(fileList, zipName) {
      const zip = new JSZip()
      for (let i = 0; i < fileList.length; i++) {
        const blob = await this.getBlobPms(fileList[i])
        zip.file(fileList[i].oldName, blob, { base64: true })
      }
      zip.generateAsync({ type: 'blob' }).then((content) => {
        // location.href = URL.createObjectURL(content)
        let name = zipName + '.zip'
        this.saveAs(content, name)
      })
    },
    //获取水印信息
    async getWatermarkInfo() {
      if (!this.$store.getters.userId) {
        this.loginTip()
        return
      }
      if (this.waterQuery.text) return
      let params = await this.$store.dispatch(
        'getDictionaryEnumListVal',
        'WATERMARK_SETTINGS',
      )
      params.forEach((item) => {
        this.waterQuery[item.msg] = item.content
      })
    },
    //获取文件流 type: 1单篇 2整册
    getBlobPms(item) {
      return new Promise((res, rej) => {
        this.waterQuery.id = item.id
        let url = this.watermarkURLOne + this.obj2Params(this.waterQuery)
        // let url =
        // (type == 1 ? this.watermarkURLOne : this.watermarkURLAll) +
        // this.obj2Params(this.waterQuery)
        var xhr = new XMLHttpRequest() // 用这种原生请求下载后端返回的二进制流打开就不会出现空白
        xhr.open('post', url, true)
        xhr.responseType = 'blob'
        xhr.onload = function () {
          res(this.response)
        }
        xhr.send()
      })
    },
    //保存
    saveAs(blob, name) {
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', name)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },
    //对象转params
    obj2Params(obj) {
      let str = '?'
      for (var key in obj) {
        str += key + '=' + obj[key] + '&'
      }
      return str.slice(0, -1)
    },
    //新增书籍下载点击数 collectType: 1 书籍  2 文章
    addDownloadCount(id, collectType = 1) {
      sysJournalCollectAdd({
        resId: id,
        opt: 'download',
        collectType,
      }).then((res) => {})
    },
  },
}
